from datetime import timedelta
from rest_framework.views import APIView
from certificate_manager.minio import MinioSingleton
from rest_framework.response import Response
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from certificate_manager.utils import save_excel
from certificate_manager.models import *

from datetime import datetime
from certificate_manager.minio import MinioSingleton

'''
现在我们的想法是什么？
我们想让其请求一个API之后用心跳的方式返回列表
但是现在时间紧迫，我们就假装数据很简单吧

target_names = ['竞赛名称', '赛事等级', '作品名称', '指导老师', '负责人', '队员', '获奖级别', '获奖时间']
'''

class GetXLSXView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request, format=None, name=None):
        data = [
            {
                '竞赛名称': cert.get_comp_name(),
                '赛事等级': cert.get_comp_level(),
                '作品名称': cert.get_name(),
                '指导老师': cert.get_user_list(DepartRestrict.ADVISOR),
                '负责人': cert.get_user_list(DepartRestrict.JOINER)[0],
                '队员': cert.get_user_list(DepartRestrict.JOINER),
                '获奖级别': str(cert.get_level()),
                '获奖时间': cert.get_achieve_date()
            }
            for cert in Cert.objects.all()
        ]

        file_name = f'{int(datetime.timestamp(datetime.now()))}.xlsx'
        file_path = f'xlsx_output/f{file_name}'

        save_excel(data, file_path)

        # 将文件上传上去
        client = MinioSingleton.getMinioServer()
        found = client.bucket_exists("geexin-xlsx")
        if not found:
            client.make_bucket("geexin-xlsx")

        result = client.fput_object(
            "geexin-xlsx", file_name, file_path,
        )

        back_url = client.presigned_get_object('geexin-xlsx', file_name, expires=timedelta(days=1))

        back_url = back_url.replace('http://localhost:9000', '/oss')

        # 这里要构造一个合法的地址
        return Response({'url': back_url})
